﻿using Agile.Infra.Core.Agile.Extensions;
using Agile.Infra.Pay.WxPay.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Security.Cryptography;
using System.Text;

namespace Agile.Infra.Pay.WxPay
{
    public partial class WxPayService : AbstractPayService, IWxPayService
    {
        private readonly WxPayOptions _wxPayOptions;

        public WxPayService(IHttpClientFactory httpClientFactory, ILogger<WxPayService> logger, IOptions<WxPayOptions> wxPayOptions) : base(httpClientFactory, logger)
        {
            _wxPayOptions = wxPayOptions.Value;
        }



        private string GetAuthorization(string timestamp, string nonceStr, string signature)
        => $"mchid=\"{_wxPayOptions.AppID}\",nonce_str=\"{nonceStr}\",signature=\"{signature}\",timestamp=\"{timestamp}\",serial_no=\"{_wxPayOptions.MchCertSerialNo}\"";

        private string GeneratePrePaySignature(string method, string url, string timestamp, string nonceStr, string body, string privateKeyPath)
        {
            // 构建签名串
            var signatureStr = $"{method}\n{url}\n{timestamp}\n{nonceStr}\n{body}\n";

            return GenerateSignature(signatureStr, privateKeyPath);
        }

        private string GenerateSignature(string signatureStr, string privateKeyPath)
        {
            // 加载私钥
            var privateKey = System.IO.File.ReadAllText(privateKeyPath);
            privateKey = privateKey
                .Replace("-----BEGIN PRIVATE KEY-----", "")
                .Replace("-----END PRIVATE KEY-----", "")
                .Replace("\n", "")
                .Trim();

            var privateKeyBytes = Convert.FromBase64String(privateKey);

            // 创建RSA实例并导入私钥
            using var rsa = RSA.Create();
            rsa.ImportPkcs8PrivateKey(privateKeyBytes, out _);

            // 计算SHA256哈希和符号
            var dataBytes = Encoding.UTF8.GetBytes(signatureStr);
            var signatureBytes = rsa.SignData(dataBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

            // Base64对签名进行编码
            return Convert.ToBase64String(signatureBytes);
        }

        private bool CheckNotifySign(HttpRequest httpRequest, WxPayNotifyRequest request)
        {
            // 获取验签数据
            var serial = httpRequest.Headers["Wechatpay-Serial"].ToString();
            var nonce = httpRequest.Headers["Wechatpay-Nonce"].ToString();
            var timestamp = httpRequest.Headers["Wechatpay-Timestamp"].ToString();
            var signature = httpRequest.Headers["Wechatpay-Signature"].ToString();

            // 构建签名串
            var signatureStr = $"{timestamp}\n{nonce}\n{request.ToJsonString()}\n";

            // 生成签名
            var sign = GenerateSignature(signatureStr, _wxPayOptions.MchCertSecretPath);

            // base64解码应答签名
            var dataBytes = Encoding.UTF8.GetBytes(signature);

            return Convert.ToHexString(dataBytes) == sign;
        }

    }
}
